import React from 'react'

import {
  apiTweetAction
} from './lookup'


// 每个推特的 Like Unlike Retweet按钮
export function ActionBtn(props) {
  // tweet: 推特本身 action: 按钮动作 didPerformAction 执行的函数 
    const {tweet, action, didPerformAction} = props
    const likes = tweet.likes ? tweet.likes : 0
    const className = props.className ? props.className : 'btn btn-primary btn-sm'
    const actionDisplay = action.display ? action.display : 'Action'
    
    // handleActionBackendBtn 后端请求返回之后 调用的函数
    const handleActionBackendBtn = (response, status) => {
      if((status === 200 || status === 201) && didPerformAction){
        didPerformAction(response, status)
      }
    }

    // 当点击了按钮 这里先到这个函数 之后调用apiTweetAction
    const handleClick = (event) => {
      event.preventDefault()
      apiTweetAction(tweet.id, action.type, handleActionBackendBtn)
    }
    const display = action.type === 'like' ? `${likes} ${actionDisplay}` : actionDisplay
    return <button className={className} onClick={handleClick}>{display}</button>
  }
  